<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <el-form :inline="true" size="normal">
            <el-form-item label="">
                <el-input placeholder="用户名" v-model="tempSearchObj.username"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handlerSanrch">查询</el-button>
                <el-button @click="resetSearch">清空</el-button>
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" @click="showAddUser">添加</el-button>
            <el-button type="danger" :disabled="userId.length === 0" @click="removeAll">批量删除</el-button>
        </div>
        <!-- 表格 -->
        <el-table :data="userData" border style="width: 100%; margin: 10px 0;"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="index" label="序号" width="80px" align="center" type="index"></el-table-column>
            <el-table-column prop="username" label="用户名" width="90"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="100"></el-table-column>
            <el-table-column prop="roleName" label="角色列表" width="90"></el-table-column>
            <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
            <el-table-column prop="gmtModified" label="更新时间" width="180" />
            <el-table-column prop="address" label="操作">
                <template v-slot="{ row }">
                    <el-button type="info" size="small" icon="el-icon-user-solid" title="分配角色"
                        @click="handlerRole(row)" />
                    <el-button type="primary" size="small" icon="el-icon-edit-outline" title="修改用户"
                        @click="handlerAdd(row)" />
                    <el-button type="danger" size="small" icon="el-icon-delete" title="删除用户"
                        @click="handlerDelete(row)" />
                </template>
            </el-table-column>
        </el-table>
        <el-pagination :current-page="pageSize" :page-sizes="[3, 5, 10, 15]" :page-size="currentPage"
            layout="prev, pager, next, jumper,->,sizes,total" :total="total" background @current-change="handlerChange"
            @size-change="handleSize">
        </el-pagination>


        <el-dialog :title="user.id ? '修改用户' : '添加用户'" :visible.sync="dialogVisible">
            <el-form status-icon label-width="100px" class="demo-ruleForm" :rules="rules" ref="userForm" :model="user">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="user.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickName">
                    <el-input v-model="user.nickName"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="user.password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrUpdate">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="设置角色" :visible.sync="dialogVisibleUser">
            <el-form status-icon label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input disabled v-model="user.username"></el-input>
                </el-form-item>
                <el-form-item label="角色列表">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                    <el-checkbox-group v-model="userRoleIds" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="roles in allRoles" :key="roles.id" :label="roles.id">{{ roles.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="resetRoleData">取消</el-button>
                <el-button @click="assignRole">保存</el-button>
            </span>
        </el-dialog>
    </el-card>
</template>

<script>
export default {
    data() {
        return {
            userData: [],
            pageSize: 1, //当前页
            currentPage: 3, //每页多少数量
            total: 0,//总数量
            userId: [],
            checkAll: false,
            allRoles: [],//所有的角色
            userRoleIds: [], // 用户的角色ID的列表
            user: {
                //收集添加用户管理的数据
                username: '',
                nickName: '',
                password: ''
            },
            //表单验证
            rules: {
                username: [{ required: true, message: '请输入用户名' },
                { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                nickName: [{ message: '请输入昵称' }],
                password: [{ required: true, message: '请输入密码' },
                { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],

            },
            searchObj: { // 包含请求搜索条件数据的对象
                username: ''
            },
            tempSearchObj: { // 收集搜索条件输入的对象
                username: ''
            },
            dialogVisible: false, //是否显示用户添加/修改的dialog
            dialogVisibleUser: false, //是否显示角色分配的dialog
            isIndeterminate: false
        }
    },
    mounted() {
        this.getUserInfo()
    },
    methods: {
        async getUserInfo(page = 1) {
            this.page = page
            let result = await this.$API.user.getPageList(this.pageSize, this.currentPage, this.searchObj)
            //console.log(result)
            this.userData = result.data.items
            this.total = result.data.total
        },
        // 处理pageSize发送改变的回调
        //每页条数
        handleSize(page) {
            //console.log(page);
            this.currentPage = page
            this.getUserInfo()
        },
        handlerChange(limit) {
            //console.log(limit);
            this.pageSize = limit
            this.getUserInfo()
        },
        showAddUser() {
            this.user = {}
            this.dialogVisible = true
            this.$nextTick(() => this.$refs.userForm.clearValidate())
        },
        // 确定按钮的回调
        addOrUpdate() {
            this.$refs['userForm'].validate(async (success) => {
                //如果成功
                if (success) {
                    let result
                    if (this.user.id) {
                        let { id, username, nickName, password } = this.user
                        result = await this.$API.user.update({ id, username, nickName, password })
                    } else {
                        result = await this.$API.user.add(this.user)
                    }
                    console.log(result);
                    this.getUserInfo()
                    //关闭弹窗
                    this.dialogVisible = false
                }
            })
        },
        //搜索回调
        handlerSanrch() {
            this.searchObj = { ...this.tempSearchObj }
            this.getUserInfo()
        },
        // 重置输入
        resetSearch() {
            this.searchObj = {
                username: ''
            }
            this.tempSearchObj = {
                username: ''
            }
            this.getUserInfo()
        },
        // 修改按钮
        handlerAdd(row) {
            this.user = {
                ...row
            }
            this.dialogVisible = true
        },
        //删除按钮
        handlerDelete(row) {
            console.log(row);
            this.$confirm(`确定删除${row.username}吗？`, {
                type: 'warning'
            }).then(async () => {
                const result = await this.$API.user.removeById(row.id)
                console.log(result);
                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
                this.getUserInfo()
            })
        },
        // 监听列表中发送状态改变
        handleSelectionChange(val) {
            this.userId = val.map(item => item.id)
        },
        // 批量删除
        removeAll() {
            this.$confirm(`确定要删除吗？`, {
                type: 'warning'
            }).then(async () => {
                let result = await this.$API.user.removeUsers(this.userId)
                console.log(result);
                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
                this.getUserInfo()
            })
        },
        // 分配角色回调
        handlerRole(row) {
            console.log(row);
            this.user = row
            // 显示弹框
            this.dialogVisibleUser = true
            this.getRole()
        },
        // 分配角色回调
        async getRole() {
            let result = await this.$API.user.getRoles(this.user.id)
            console.log(result);
            let { allRolesList, assignRoles } = result.data
            this.allRoles = allRolesList
            this.userRoleIds = assignRoles.map(item => item.id)
            this.checkList = allRolesList.length === assignRoles.length
            this.isIndeterminate = assignRoles.length > 0 && assignRoles.length < allRolesList.length

        },
        //全选的回调
        handleCheckAllChange(val) {
            // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
            this.userRoleIds = val ? this.allRoles.map(item => item.id) : []
            // 如果当前不是全选也不全不选时, 指定为false
            this.isIndeterminate = false
        },
        handleCheckedCitiesChange(value) {
            const { userRoleIds, allRoles } = this
            this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
            this.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
        },
        //保存按钮
        async assignRole() {
            const userId = this.user.id
            const roleIds = this.userRoleIds.join(',')
            const result = await this.$API.user.assignRoles(userId, roleIds)
            this.$message.success(result.message || '分配角色成功')
            this.getUserInfo()
            if (this.$store.getters.name === this.user.username) {
                window.location.reload()
            }
            this.dialogVisibleUser = false
        },
        resetRoleData() {
            this.dialogVisibleUser = false
            this.allRoles = []
            this.userRoleIds = []
        }

    }
}
</script>

<style lang="scss" scoped>

</style>